package cn.demomaster.quickui.util;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.view.View;
import android.view.ViewTreeObserver;

import com.demomaster.quickcompat.util.DisplayUtil;
import com.demomaster.quickcompat.util.QDBitmapUtil;

import cn.demomaster.quicklogger.QdLog;
import cn.demomaster.quickrouter.OnReleaseListener;

/**
 * 毛玻璃特效帮助类
 */
public class GroundGlassUtil implements OnReleaseListener {
    private View targetView;
    private View parentView;
    Context context;
    MyAsyncTask myAsyncTask;

    public GroundGlassUtil(Context context) {
        this.context = context;
    }

    private int backgroundColor = 0x55ffffff;
    private boolean useBackgroundColor = true;

    public void setUseBackgroundColor(boolean useBackgroundColor) {
        this.useBackgroundColor = useBackgroundColor;
        invalidate();
    }

    public void setBackgroundColor(int backgroundColor) {
        this.backgroundColor = backgroundColor;
        invalidate();
    }

    public View getTargetView() {
        return targetView;
    }

    boolean targetViewLoadComplete = false;

    public void addView(View targetView) {

    }
    public void setTargetView(View targetView) {
        this.targetView = targetView;
        if (parentView == null) {
            if (targetView.getParent() instanceof View) {
                parentView = (View) targetView.getParent();
                setParentView(parentView);
            }
        }
        if(onGlobalLayoutListener_TargetView==null) {
            onGlobalLayoutListener_TargetView = new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    targetView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    QdLog.println("在这里处理View显示完成后的逻辑");
                    targetViewLoadComplete = true;
                    isChangeVisibility = true;
                }
            };
        }else {
            targetView.getViewTreeObserver().removeOnGlobalLayoutListener(onGlobalLayoutListener_TargetView);
        }
        targetView.getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener_TargetView);
    }

    public void setParentView(View view) {
        this.parentView = view;
        onGlobalLayoutListener_ParentView = new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (onParentViewDrawListener == null) {
                    onParentViewDrawListener = () -> {
                        if (targetViewLoadComplete) {
                            if (!isChangeVisibility) {
                                // QdLog.println("viewParent重绘重新模糊处理");
                                invalidate();
                            } else {
                                isChangeVisibility = false;
                            }
                        }
                    };
                    //view重绘时回调
                    if(parentView!=null) {
                        parentView.getViewTreeObserver().addOnDrawListener(onParentViewDrawListener);
                    }
                }
            }
        };
        parentView.getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener_ParentView);
    }

    boolean autoFindBackgroundView;//自动寻找待截图对象
    ViewTreeObserver.OnDrawListener onParentViewDrawListener;
    ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener_ParentView;
    ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener_TargetView;

    boolean isBluring;//正在模糊处理

    //boolean hasResidue;//遗留的任务
    public void invalidate() {
        if (targetView == null || targetView.getVisibility() == View.GONE) {
            return;
        }
        if (isBluring) {
            return;
        }
        isBluring = true;

        Bitmap bitmap = shootBackgroundBitmap();
        if (bitmap == null) {
            isBluring = false;
        }

        if (myAsyncTask != null) if (!myAsyncTask.isCancelled()) {
            myAsyncTask.cancel(true);
            myAsyncTask.setView(null);
            myAsyncTask.setGroundGlassUtil(null);
            myAsyncTask = null;
        }

        myAsyncTask = new MyAsyncTask(this, targetView);
        myAsyncTask.execute(bitmap);
    }

    Bitmap mBackgroundBitmap;

    /**
     * 获取待模糊的图片
     *
     * @return
     */
    private Bitmap generateBackgroundBitmap(Bitmap backgroundBitmap) {
        if (backgroundBitmap == null) {
            return null;
        }
        long t1 = System.currentTimeMillis();
        //compareBitmap = QDBitmapUtil.areBitmapsEqual(backgroundBitmap,mBackgroundBitmap);
        boolean compareBitmap = false;//对比图片是否有变化
        //对比两张图片是否一致
        if (mBackgroundBitmap != null) {
            compareBitmap = QDBitmapUtil.compare2Bitmap(backgroundBitmap, mBackgroundBitmap, 5);
        }
        long t2 = System.currentTimeMillis();
        QdLog.println("图片对比：" + compareBitmap + ",用时" + (t2 - t1));
        mBackgroundBitmap = backgroundBitmap;
        if (compareBitmap) {
            return null;
        }

        long t11 = System.currentTimeMillis();
        //缩放尺寸
        Bitmap bitmap = QDBitmapUtil.zoomBitmap(backgroundBitmap, (int) (backgroundBitmap.getWidth() / 4f), (int) (backgroundBitmap.getHeight() / 4f));
        //模糊背景
        bitmap = BlurUtil.doBlur(bitmap, radius, 0.2f);
        long t12 = System.currentTimeMillis();
        //QdLog.println("模糊用时：" + (t12 - t11));
        //添加背景色
        if (useBackgroundColor) {
            Bitmap colorBitmap = QDBitmapUtil.generateColorBitmap(bitmap.getWidth(), bitmap.getHeight(), backgroundColor);
            bitmap = QDBitmapUtil.mergeBitmap(bitmap, colorBitmap);
            //long t3 = System.currentTimeMillis();
            //QdLog.println("添加背景色用时：" + (t3 - t2));
        }
        //bitmap = getAlplaBitmap(bitmap, 80);
        return bitmap;
    }

    boolean isChangeVisibility = true;//正在改变view显示状态 这种变化会导致父类view重绘  需要过滤掉

    /**
     * 获取背景图片
     *
     * @return
     */
    private Bitmap shootBackgroundBitmap() {
        if(parentView==null){
            return null;
        }
        //获取覆盖区域
        int[] location_parent = new int[2];
        parentView.getLocationOnScreen(location_parent);//获取在整个屏幕内的绝对坐标
        //tabGroup.getLocationInWindow(location); //获取在当前窗口内的绝对坐标
        //parentView.getLocationOnScreen(location_background);//获取在整个屏幕内的绝对坐标
        //Rect rect_background = new Rect(location_background[0], location_background[1], location_background[0] + parentView.getWidth(), location_background[1] + parentView.getHeight());
        //QdLog.println("x=" + location_background[0] + ",y=" + location_background[1]);

        int[] location_target = new int[2];
        targetView.getLocationOnScreen(location_target);//获取在整个屏幕内的绝对坐标
        Rect visibleRect = new Rect();
        targetView.getGlobalVisibleRect(visibleRect);
        //Rect rect_target = new Rect(location_target[0], location_target[1], location_target[0] + visibleRect.width(), location_target[1] + visibleRect.height());

        //获取绝对坐标的交集
//        Rect rect3 = getBothArea(rect_background, rect_target);
//        if (rect3.width() <= 0 || rect3.height() <= 0) {
//            return null;
//        }

        boolean isVisible = false;
        if (targetView.getVisibility() == View.VISIBLE) {
            isVisible = true;
            isChangeVisibility = true;
            targetView.setVisibility(View.INVISIBLE);
        }
        // Bitmap bitmap = shot(parentView, rect4.left, rect4.top, rect4.width(), rect4.height());
        long t1 = System.currentTimeMillis();
        // Bitmap bitmap =  ScreenShotUitl.shotActivity((Activity) context, true); //shot(parentView, rect_target.left, rect_target.top, rect_target.width(), rect_target.height());
        Bitmap bitmap = ScreenShotUitl.takeScreenshot2((Activity) context, parentView);//ScreenShotUitl.getCacheBitmapFromView(view);//
        long t2 = System.currentTimeMillis();
        //QdLog.println("截图：用时" + (t2 - t1));
        if (isVisible) {
            targetView.setVisibility(View.VISIBLE);
        }

        //Rect rectc = new Rect(left, top, right, bottom);
        if (visibleRect.width() > 0 && visibleRect.height() > 0
                && visibleRect.left >= 0
                && visibleRect.left < DisplayUtil.getScreenWidth(context)
                && visibleRect.right > visibleRect.left
                && visibleRect.right < DisplayUtil.getScreenWidth(context)) {
            Bitmap bitmap2 = Bitmap.createBitmap(targetView.getMeasuredWidth(), targetView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
            int tt= visibleRect.top - location_parent[1];
            QdLog.println("location_parent[1]="+location_parent[1]+",visibleRect.top="+visibleRect.top+",tt="+tt);
            //获取view对应的截图
            Bitmap bitmap3 = QDBitmapUtil.cropBitmap2(bitmap, visibleRect.left - location_parent[0], visibleRect.top - location_parent[1], visibleRect.width(), visibleRect.height());
            if (location_target[0] + targetView.getMeasuredWidth() > (DisplayUtil.getScreenWidth(context))) {//补齐右边
                QdLog.println("view没入右边界");
                return QDBitmapUtil.mergeImages(bitmap2, bitmap3, 0, 0);
            }
            if (location_target[0] < 0) {//补齐右边
                QdLog.println("view没入左边界");
                return QDBitmapUtil.mergeImages(bitmap2, bitmap3, bitmap2.getWidth() - bitmap3.getWidth(), 0);
            }
            return bitmap3;
        }
        return null;
    }

    /**
     * 获取交集
     *
     * @param r1
     * @param r2
     * @return
     */
    public static Rect getBothArea(Rect r1, Rect r2) {
        Rect both = new Rect();
        both.left = Math.max(r1.left, r2.left);
        both.right = Math.min(r1.right, r2.right);
        both.top = Math.max(r1.top, r2.top);
        both.bottom = Math.min(r1.bottom, r2.bottom);
        return both;
    }

    public int radius = 20;

    public void setRadius(int radius) {
        this.radius = radius;
    }

    public Bitmap blurView(View view,int left,int top,int width,int height){
        Bitmap bitmap =ScreenShotUitl.takeScreenshot2((Activity) context,view);
        //bitmap = BlurUtil.doBlur(bitmap, radius, 0.2f);
        Bitmap bitmap1 = BlurUtil.doBlur(bitmap, 50, 0.2f);
        return null;
    }

    public static Bitmap blurDrawble(Drawable drawable,int width,int height){
        Bitmap bitmap1 = QDBitmapUtil.drawable2Bitmap(drawable);
        return blurBitmap(bitmap1,width,height);
    }
    public static Bitmap blurBitmap(Bitmap bitmap,int width,int height){
        Bitmap colorBitmap = QDBitmapUtil.generateColorBitmap(width, height, 0xaaffffff);//backgroundColor);
        Bitmap bitmap3 = QDBitmapUtil.mergeImages(bitmap,colorBitmap,0,0);
        Bitmap bitmap4 = BlurUtil.doBlur(bitmap3, 50, 0.4f);
        return QDBitmapUtil.setAlpha(bitmap4,80);
    }


    public static Bitmap blurColor(int width, int height, int mainColor) {
        Bitmap colorBitmap = QDBitmapUtil.generateColorBitmap(width, height, 0xddffffff);//backgroundColor);
        Bitmap colorBitmap1 = QDBitmapUtil.generateColorBitmap(width, height, mainColor);//backgroundColor);
        Bitmap bitmap3 = QDBitmapUtil.mergeImages(colorBitmap1,colorBitmap,0,0);
        Bitmap bitmap4 = BlurUtil.doBlur(bitmap3, 50, 0.4f);
        return QDBitmapUtil.setAlpha(bitmap4,140);
    }

    /**
     * 替换透明色为
     *
     * @param sourceImg
     * @param color
     * @return
     */
    public static Bitmap fillPixBitmap(Bitmap sourceImg, int color) {
        Bitmap imageWithBG = Bitmap.createBitmap(sourceImg.getWidth(), sourceImg.getHeight(), sourceImg.getConfig());  // Create another image the same size
        imageWithBG.eraseColor(color);  // set its background to white, or whatever color you want
        Canvas canvas = new Canvas(imageWithBG);  // create a canvas to draw on the new image
        canvas.drawBitmap(sourceImg, 0f, 0f, null); // draw old image on the background
        sourceImg.recycle();
        return imageWithBG;
    }

    public static Bitmap setAlplaBitmap(Bitmap sourceImg, int number) {
        int[] argb = new int[sourceImg.getWidth() * sourceImg.getHeight()];
        sourceImg.getPixels(argb, 0, sourceImg.getWidth(), 0, 0, sourceImg.getWidth(), sourceImg.getHeight());
        number = number * 255 / 100;
        for (int i = 0; i < argb.length; i++) {
            argb[i] = (number << 24) | (argb[i] & 0x00FFFFFF);
        }
        sourceImg = Bitmap.createBitmap(argb, sourceImg.getWidth(), sourceImg.getHeight(), Bitmap.Config.ARGB_8888);
        return sourceImg;
    }

    @Override
    public void onRelease(Object self) {
        if (onGlobalLayoutListener_TargetView != null&&targetView!=null) {
            targetView.getViewTreeObserver().removeOnGlobalLayoutListener(onGlobalLayoutListener_TargetView);
        }
        if(onGlobalLayoutListener_TargetView != null){
            onGlobalLayoutListener_TargetView = null;
        }
        if (onParentViewDrawListener != null&&parentView!=null) {
            parentView.getViewTreeObserver().removeOnDrawListener(onParentViewDrawListener);
        }
        if(onParentViewDrawListener != null){
            onParentViewDrawListener = null;
        }
        if (onGlobalLayoutListener_ParentView != null&&parentView!=null) {
            parentView.getViewTreeObserver().removeOnGlobalLayoutListener(onGlobalLayoutListener_ParentView);
        }

        if(onGlobalLayoutListener_ParentView != null){
            onGlobalLayoutListener_ParentView = null;
        }

        if (myAsyncTask != null) {
            if (!myAsyncTask.isCancelled()) {
                myAsyncTask.cancel(true);
            }
            myAsyncTask.setView(null);
            myAsyncTask.setGroundGlassUtil(null);
            myAsyncTask = null;
        }

        parentView = null;
        targetView = null;
    }

    public class MyAsyncTask extends AsyncTask {
        View view;
        GroundGlassUtil groundGlassUtil;

        public MyAsyncTask(GroundGlassUtil groundGlassUtil, View view) {
            this.groundGlassUtil = groundGlassUtil;
            this.view = view;
        }

        @Override
        protected Object doInBackground(Object[] objects) {
            isBluring = true;
            if (objects != null && objects.length > 0 && objects[0] instanceof Bitmap) {
                //return ((Bitmap) objects[0]);
                Bitmap bitmap = groundGlassUtil.generateBackgroundBitmap((Bitmap) objects[0]);
                return bitmap;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            isBluring = false;
            if (o instanceof Bitmap) {
                //setViewBackground((Bitmap) o);
                view.setBackground(new BitmapDrawable(context.getResources(), (Bitmap) o));
            }
            view = null;
            groundGlassUtil = null;
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            isBluring = false;
        }

        public void setView(View v) {
            view = v;
        }

        public void setGroundGlassUtil(GroundGlassUtil groundGlassUtil) {
            this.groundGlassUtil = groundGlassUtil;
        }
    }
}
